<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2007 by CPG-Nuke Dev Team
  http://dragonflycms.org

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version
**********************************************/
if (!defined('ADMIN_PAGES')) { exit; }
if (!can_admin('modules')) { die('Access Denied'); }

$K   = Dragonfly::getKernel();
$L10N = $K->L10N;
$L10N->load('dragonfly/blocks');

if (isset($_GET['change'])) {
	if ('modules' != $CPG_SESS['admin']['page']) { cpg_error(_ERROR_BAD_LINK, _SEC_ERROR); }
	$mid = intval($_GET['change']);
	$result = $db->query("SELECT active FROM {$db->TBL->modules} WHERE mid={$mid} AND title<>'Your_Account'");
	if ($result->num_rows) {
		list($active) = $result->fetch_row();
		$db->TBL->modules->update(array('active'=>!$active), "mid={$mid}");
	}
	Cache::clear_conf();
	URL::redirect(URL::admin('modules'));
}

else if (isset($_GET['a'])) {
	if (isset($_POST['confirm'])) {
		if ('all' == $_GET['a']) {
			$db->TBL->modules->update(array('active'=>1), "title<>'Your_Account'");
		} else if ('none' == $_GET['a']) {
			$db->TBL->modules->update(array('active'=>0), "title<>'Your_Account'");
		}
		Cache::clear_conf();
	} else if (!isset($_POST['cancel'])) {
		if ($_GET['a'] == 'all') {
			$a = 'all';
			$msg = sprintf(_SURETO,_ACTIVATE,_MODULES);
		} else {
			$a = 'none';
			$msg = sprintf(_SURETO,_DEACTIVATE,_MODULES);
		}
		cpg_delete_msg(URL::admin("&amp;a=$a"), $msg);
	}
	URL::redirect(URL::admin('modules'));
}

else if (isset($_GET['home'])) {
	$mid = intval($_GET['home']);
	list($title) = $db->uFetchRow("SELECT title FROM {$db->TBL->modules} WHERE mid={$mid}");
	if (isset($_POST['confirm'])) {
		if ($CPG_SESS['admin']['page'] != 'modules') { cpg_error(_ERROR_BAD_LINK, _SEC_ERROR); }
		$db->TBL->config_custom->update(array('cfg_value'=>$title), "cfg_field='main_module' AND cfg_name='global'");
		$db->TBL->modules->update(array('active'=>1), "mid={$mid}");
		Cache::clear_conf();
	} else if (!isset($_POST['cancel'])) {
		cpg_delete_msg(URL::admin('&amp;home='.$mid), _SURETOCHANGEMOD.' <strong>'.$MAIN_CFG['global']['main_module'].'</strong> '._TO." <strong>{$title}</strong>?");
	}
	URL::redirect(URL::admin('modules'));
}

else if (isset($_GET['edit'])) {
	$mid = intval($_GET['edit']);

	if (isset($_POST['upgrade'])) {
	//	if ($CPG_SESS['admin']['page'] != 'modules') { cpg_error(_ERROR_BAD_LINK, _SEC_ERROR); }
		define('ADMIN_MOD_INSTALL', 1);
		list($modname, $version) = $db->uFetchRow("SELECT title, version FROM {$db->TBL->modules} WHERE mid={$mid}");
		if (!$installer = new Installer_Module($modname)) {
			cpg_error($installer->error, 'Could not initiate the upgrade');
		}
		Cache::clear_conf();
		if (!$installer->upgrade_module($version)) {
			cpg_error(_UPGRADEFAILED .': ' .$installer->error, _UPGRADEFAILED);
		}
		cpg_error(_TASK_COMPLETED, 'Module upgrade suceeded', DF_MODE_DEVELOPER ? false : URL::admin('modules'));
	}

	list($title, $custom_title, $view, $inmenu, $blocks, $version) = $db->uFetchRow("SELECT title, custom_title, view, inmenu, blocks, version FROM {$db->TBL->modules} WHERE mid={$mid}");
	$blocks = intval($blocks);
	Dragonfly_Page::setTitle(_MODULEEDIT);
	$inst_file = is_file('modules/'.$title.'/cpg_inst.php') ? 'modules/'.$title.'/cpg_inst.php' : false;
	$inst_file = !$inst_file && is_file('modules/'.$title.'/install/cpg_inst.php') ? 'modules/'.$title.'/install/cpg_inst.php' : false;
	if ($inst_file) {
		define('ADMIN_MOD_INSTALL', 1);
		include($inst_file);
		if (class_exists($title)) {
			$editmodule = new $title;
		}
	}
	require('header.php');
	OpenTable();
	$a = ($title == $MAIN_CFG['global']['main_module']) ? ' - ('._INHOME.')' : '';
	echo open_form(URL::admin('modules'), '', ($title.$a))
	.'<label class="ulog" for="custom_title">'._CUSTOMTITLE.'</label>
	<input type="text" name="custom_title" id="custom_title" value="'.$custom_title.'" size="30" maxlength="255" /><br />';
	if ($title == $MAIN_CFG['global']['main_module']) {
		echo '<input type="hidden" name="view" value="0" />';
	} else {
		echo '<label class="ulog" for="view">'._VIEWPRIV.'</label>'.group_selectbox('view', $view).'<br />';
	}
	echo '<label class="ulog" for="inmenu">'._SHOWINMENU.'</label>'.yesno_option('inmenu', $inmenu).'<br />
	<input type="hidden" name="save" value="'.$mid.'" />
	<input type="submit" value="'._SAVECHANGES.'" />'
	.close_form();
	if (isset($editmodule)) {
		$dbsize = 0;
		$backup = '';
		if (isset($editmodule->dbtables) && !empty($editmodule->dbtables)) {
			if (0 === strpos(SQL_LAYER, 'mysql')) {
				if ($result = $db->query("SHOW TABLE STATUS FROM $dbname")) {
					while ($table = $result->fetch_assoc()) {
						if (in_array(substr($table['Name'], strlen($prefix)+1), $editmodule->dbtables) &&
							((isset($table['Type']) && $table['Type'] != 'MRG_MyISAM') || (isset($table['Engine']) && $table['Engine'] != "MRG_MyISAM"))
						) {
							$dbsize += $table['Data_length'] + $table['Index_length'];
						}
					}
				}
			}
			$backup = '<label class="ulog">'._DBSIZE.'</label>'.filesize_to_human($dbsize).', <a href="'.URL::admin('&amp;backup='.$title).'">'._SAVEDATABASE.'</a><br />';
		}
		if (strlen($editmodule->website) > 3) $author = '<a href="http://'.$editmodule->website.'" target="_blank">'.$editmodule->author.'</a>';
		else $author = $editmodule->author;
		echo '<form action="" method="post">
		<fieldset><legend><b>'._TB_INFO.'</b></legend>
		<label class="ulog">'._CREDITS_AUTHORS.'</label>'.$author.'<br />
		<label class="ulog">'._CREDITS_DESC.'</label>'.$editmodule->description.'<br />
		<label class="ulog">'._VERSION.'</label>'.$version;
		if (version_compare($version, $editmodule->version, '<')) {
			echo ' <button type="submit" name="upgrade">'.sprintf(_UPGRADE, $editmodule->version).'</button>';
		}
		elseif (version_compare($version, $editmodule->version, '>')) {
			echo ' <button type="submit" name="downgrade">Downgrade to version '.$editmodule->version.'</button>';
		}
		echo '<br />
		'.$backup.'
		</fieldset>
		</form>';
	}
	CloseTable();
}

else if (isset($_GET['backup'])) {
	if (!preg_match('#^([a-zA-Z0-9_\-]+)$#', $_GET['backup'])) {
		cpg_error(sprintf(_ERROR_NO_EXIST,_FILENAME));
	}
	$class = $_GET['backup'];
	$path = 'modules/'.$_GET['backup'];
	$inst_file = is_file($path.'/cpg_inst.php') ? $path.'/cpg_inst.php' : false;
	$inst_file = !$inst_file && is_file($path.'/install/cpg_inst.php') ? $path.'/install/cpg_inst.php' : false;
	if ($inst_file) {
		define('ADMIN_MOD_INSTALL', 1);
		include($inst_file);
		if (class_exists($class)) {
			$m = new $class;
			$tables = array();
			require_once(CORE_PATH.'classes/sqlctrl.php');
			foreach($m->dbtables AS $table) {
				$tables[] = $prefix.'_'.$table;
			}
			SQLCtrl::backup($dbname, $tables, str_replace(' ', '_', $m->modname).'.sql');
		}
	}
}

else if (isset($_POST['save'])) {
	if ($CPG_SESS['admin']['page'] != 'modules') { cpg_error(_ERROR_BAD_LINK, _SEC_ERROR); }
	$mid = intval($_POST['save']);
	$result = $db->query("SELECT title FROM {$db->TBL->modules} WHERE mid={$mid}");
	if ($result->num_rows) {
		list($title) = $result->fetch_row();
		$db->TBL->modules->update(array(
			'custom_title' => $_POST['custom_title'],
			'view'   => ('Your_Account' == $title) ? 0 : intval($_POST['view']),
			'inmenu' => intval($_POST['inmenu'])
		),"mid={$mid}");
		//Dragonfly::getKernel()->CACHE->delete('blocks_list');
	}
	URL::redirect(URL::admin('modules'));
}

else {
	define('ADMIN_MOD_INSTALL', 1);

	if (isset($_GET['install']) && preg_match('#^[a-z0-9_\-]+$#i', $_GET['install'])) {
		if ($CPG_SESS['admin']['page'] != 'modules') { cpg_error(_ERROR_BAD_LINK, _SEC_ERROR); }
		$modname = $_GET['install'];
		if (!$installer = new Installer_Module($modname)) {
			cpg_error($installer->error, 'Module install failed');
		}
		if (!$installer->add_module()) {
			cpg_error($installer->error, 'Module install failed');
		}
		Cache::clear_conf();
		cpg_error('The module "'.$modname.'" has been properly installed, have a blast using it!', 'Module install succeeded', DF_MODE_DEVELOPER ? false : URL::admin('modules'));
	}

	else if (isset($_GET['uninstall']) && preg_match('#^[a-z0-9_\-]+$#i', $_GET['uninstall'])) {
		if ($CPG_SESS['admin']['page'] != 'modules') { cpg_error(_ERROR_BAD_LINK, _SEC_ERROR); }
		$modname = $_GET['uninstall'];
		if (isset($_POST['confirm']) && Security::check_post()) {
			if (!$installer = new Installer_Module($modname)) {
				cpg_error($installer->error, 'Module uninstall failed');
			}
			if (!$installer->remove_module()) {
				cpg_error($installer->error, 'Module uninstall failed');
			}
			Cache::clear_conf();
			cpg_error('The module "'.$modname.'" has been properly uninstalled, you can safely delete the files associated with it', 'Module uninstall succeeded', DF_MODE_DEVELOPER ? false : URL::admin('modules'));
		} else if (!isset($_POST['cancel'])) {
			cpg_delete_msg(URL::admin('&amp;uninstall='.$modname), 'Are you sure that you want to remove all data associated with <strong>'.$modname.'</strong>?');
		}
		URL::redirect(URL::admin('modules'));
	}

	$mods = array();
	$result = $db->query("SELECT mid, title, custom_title, version, active, view, inmenu, uninstall, blocks FROM {$db->TBL->modules}");
	while ($row = $result->fetch_assoc()) {
		if (!file_exists("modules/{$row['title']}/index.php")) {
			$db->TBL->modules->delete("mid={$row['mid']}");
			$db->optimize($db->TBL->modules);
			$db->TBL->blocks_custom->delete("mid={$row['mid']}");
			$db->optimize($db->TBL->blocks_custom);
			//Dragonfly::getKernel()->CACHE->delete('blocks_list');
		} else {
			if (is_file('modules/'.$row['title'].'/install/cpg_inst.php')) {
				include('modules/'.$row['title'].'/install/cpg_inst.php');
				if (class_exists($row['title'])) {
					$m = new $row['title'];
					$row['needs_upgrade'] = version_compare($row['version'], $m->version, '<');
				}
			}
			$mods[$row['title']] = $row;
		}
	}

	$handle = Dragonfly_Modules::ls('index.php', false);
	foreach ($handle as $class => $file) {
		if (!isset($mods[$class])) {
			$inst_file = is_file('modules/'.$class.'/cpg_inst.php') ? 'modules/'.$class.'/cpg_inst.php' : false;
			if (!$inst_file) {
				$inst_file = is_file('modules/'.$class.'/install/cpg_inst.php') ? 'modules/'.$class.'/install/cpg_inst.php' : false;
			}
			$mod = array('title' => $class, 'custom_title' => '', 'active' => 0, 'view' => 0, 'inmenu' => 1, 'uninstall' => 0);
			if (is_file('modules/'.$class.'/install/cpg_inst.php')) {
				include('modules/'.$class.'/install/cpg_inst.php');
				$mod['mid'] = 0;
				if (class_exists($class)) {
					$m = new $class;
					$mod['custom_title'] = $m->description;
					$mod['uninstall']    = -1;
				} else {
					$mod['custom_title'] = "modules/{$class}/cpg_inst.php is missing class: {$class}";
				}
			} else {
				$mod['mid'] = $db->TBL->modules->insert($mod,'mid');
				$result = $db->query("SELECT bid, bposition FROM {$db->TBL->blocks} WHERE active=1");
				if ($result->num_rows) {
					$in_modules = array();
					$l = $c = $r = $d = 0;
					while ($row = $result->fetch_row()) {
						$in_modules[] = "({$row[0]}, '{$mod['mid']}', '{$row[1]}', ".++$$row[1].")";
					}
					$db->query("INSERT INTO {$db->TBL->blocks_custom} (bid, mid, side, weight) VALUES ".implode(',', $in_modules));
					//Dragonfly::getKernel()->CACHE->delete('blocks_list');
				}
				$result->free();
			}
			$mods[$class] = $mod;
		}
	}

	Dragonfly_Page::setTitle(_MODULESADMIN);
	require('header.php');
	$cpgtpl->assign_var('S_ACTION', URL::admin());

	foreach ($mods AS $title => $row) {
		$title = (defined('_'.$row['title'].'LANG'))? (constant('_'.$row['title'].'LANG')) : str_replace('_', ' ', $row['title']);
		$allmods[$title] = $row;
	}
	uksort($allmods, 'strnatcasecmp');
	while (list($title, $row) = each($allmods))
	{
		$mid = $row['mid'];
		if (($row['active'] != 1 || $row['view'] != 0) &&
		    ($row['title'] == 'Your_Account' || $row['title'] == $MAIN_CFG['global']['main_module'])) {
			$row['view'] = 0;
			$db->TBL->modules->update(array('active'=>1,'view'=>0), "mid={$mid}");
		}

		$moduledir = $row['title'];

		if ($row['view'] == 0) {
			$who_view = _MVALL;
		} elseif ($row['view'] == 1) {
			$who_view = _MVUSERS;
		} elseif ($row['view'] == 2) {
			$who_view = _MVADMIN;
		} elseif ($row['view'] > 3) {		// <= phpBB User Groups Integration
			list($who_view) = $db->uFetchRow("SELECT group_name FROM {$db->TBL->bbgroups} WHERE group_id=".($row['view']-3));
		}

		$sides = array();
		if (isset($row['blocks'])) {
			$row['blocks'] = intval($row['blocks']);
			if ($row['blocks'] == 0) $sides[] = _NONE;
			if ($row['blocks'] & Blocks::LEFT)   $sides[] = $L10N->get('Left');
			if ($row['blocks'] & Blocks::RIGHT)  $sides[] = $L10N->get('Right');
			if ($row['blocks'] & Blocks::CENTER) $sides[] = $L10N->get('Center Up');
			if ($row['blocks'] & Blocks::DOWN)   $sides[] = $L10N->get('Center Down');
		}

		$cpgtpl->assign_block_vars('mod', array(
			'B_HOME' => $row['title'] == $MAIN_CFG['global']['main_module'],
			'B_FORCE_ACTIVE' => $row['title'] == 'Your_Account',
			'B_ACTIVE' => $row['active'],
			'B_HIDDEN' => $row['title'] != $MAIN_CFG['global']['main_module'] && !$row['inmenu'],
			'B_WITH_SQL' => 1 == $row['uninstall'],
			'B_NOT_INSTALLED' => 0 > $row['uninstall'],
			'S_CLASS' => !empty($row['needs_upgrade']) ? 'upgrade' : (0 > $row['uninstall'] ? 'install' : ''),
			'S_MID' => $row['mid'],
			'S_NAME' => $row['title'],
			'S_TITLE' => $title,
			'S_CUSTOM_TITLE' => $row['custom_title'],
			'S_VIEW' => $who_view,
			'S_BLOCKS' => implode(', ', $sides),
			'U_INDEX' => URL::index($moduledir),
			'U_EDIT' => URL::admin('&amp;edit='.$row['mid']),
			'U_CHANGE' => URL::admin('&amp;change='.$mid),
			'U_INSTALL' => URL::admin("&amp;install={$moduledir}"),
			'U_UNINSTALL' => URL::admin("&amp;uninstall={$moduledir}"),
			'U_SET_HOME' => URL::admin("&amp;home={$mid}"),
		));

	}
	$cpgtpl->set_handle('body', 'admin/modules.html');
	$cpgtpl->display('body');
}
